﻿using BassTutor.Model;
using BassTutor.Analysis;
using BassTutor.Properties;
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace BassTutor.GUI
{
    class ViewModel
    {
        private SoundAnaliser analiser;
        private SoundCapture source;
        private Note ExpectedNote;
        private static Random rnd = new Random();
        
        public DrawingImage Paint { get; set; }
        private DrawingGroup scene;

        internal ViewModel()
        {
            Generate();
            ExpectedNote = new Note(rnd.Next(0, 40), Note.Color.Blue);
            source = new SoundCapture();
            try
            {
                analiser = new SoundAnaliser(source);
            }
            catch (Exception e) { 
                e.Handle();
                System.Environment.Exit(-1);
            }
            analiser.NoteRecognized += Refresh;
            source.Start();
            Refresh();
        }

        private void Generate()
        {
            try
            {
                Paint = new DrawingImage();
                scene = new DrawingGroup();

                ImageDrawing background = new ImageDrawing();
                background.ImageSource = Resources.Background.ToImageSource();
                background.Rect = new Rect(0, 0, background.ImageSource.Width, background.ImageSource.Height);

                scene.Children.Add(background);

                Paint.Drawing = scene;
            }
            catch (Exception e) { e.Handle(); }
        }

        private void Refresh(Note PlayedNote=null)
        {
            new NoteGlyph(ExpectedNote).Draw(scene);
            if(PlayedNote!=null)
                new NoteGlyph(PlayedNote).Draw(scene);
        }
    }
}
